#!/usr/bin/env python3

import urllib.request
import urllib.parse
import multiposter

class DoubanAPIError(Exception):
    code=''
    reason='unkown error'
    response=''
    def __init__(self, resp):
        if isinstance(resp, urllib.error.HTTPError):
            self.code = resp.code
            self.reason = resp.reason
            self.response = resp.read().decode('utf-8')

    def __str__(self):
        return "******(%s:%s)\n******%s" % (self.code,self.reason,self.response)

class ApiService(object):
    def __init__(self, access_token):
        self.access_token = access_token

    def post(self, url, datas=None):
        return self.sendRequest(url,datas,'POST')

    def delete(self, url):
        return self.sendRequest(url, None, 'DELETE')

    def put(self, url, datas):
        return self.sendRequest(url, datas, 'PUT')

    def get(self, url):
        return self.sendRequest(url, None, 'GET')

    def multi_post(self, url, fields, files):
        try:
            return multiposter.post_multipart(url, fields, files,
            [('Authorization','Bearer ' + self.access_token)])
        except Exception as e:
            raise e
            #return DoubanAPIError(e)

    def sendRequest(self, url, datas=None, method=None):
        print('###################################################')
        print(url)
        print(datas)
        if datas != None:
            datas = urllib.parse.urlencode(datas)
            datas = datas.encode('utf-8')

        if method == 'POST':
            req = urllib.request.Request(url=url, method='POST')
            req.add_header("Authorization", "Bearer " + self.access_token)
            try:
                f = urllib.request.urlopen(req, datas)
                return f.read().decode('utf-8')
            except Exception as e:
                print(DoubanAPIError(e))
                return DoubanAPIError(e)
        elif method == 'GET':
            req = urllib.request.Request(url)
        elif method == 'PUT':
            req = urllib.request.Request(url=url, data=datas, method='PUT')
        elif method == 'DELETE':
            req = urllib.request.Request(url=url, method='DELETE')
        req.add_header("Authorization", "Bearer " + self.access_token)
        try:
            f = urllib.request.urlopen(req)
            return f.read().decode('utf-8')
        except Exception as e:
            print(DoubanAPIError(e))
            return DoubanAPIError(e)
        
